/*
采用 getaddrinfo 传入主机名和服务名实现的 UDP 时间获取服务端。
**/

#include <define.h>
#include <error.h>
#include <wrapfunc.h>
#include <sockfunc.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stddef.h>
#include <time.h>
#include <stdio.h>
#include <string.h>


int
main(int argc, char **argv) {
    if (argc != 2 && argc != 3)
        error_quit("usage: %s [host] service", argv[0]);
    const char *host = NULL;
    const char *service = NULL;
    if (argc == 2) {
        service = argv[1];
    } else if (argc == 3) {
        host = argv[1];
        service = argv[2];
    }

    int sockfd = Udp_server(host, service, NULL);
    struct sockaddr_storage ss;
    socklen_t len;
    char buf[MAX_LINE];
    for (;;) {
        len = sizeof(ss);
        Recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr*)&ss, &len);
        error_msg("recv datagram from %s", sock_ntop((struct sockaddr*)&ss, len));
        
        time_t tick;
        time(&tick);
        snprintf(buf, sizeof(buf), "%.24s", ctime(&tick));
        Sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr*)&ss, len);
    }
    Close(sockfd);
    
    return 0;
}
